#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <mqueue.h>
#include <stdlib.h>

static char *mq_name = "/my_queue";
static mqd_t mq;
void *first_thread_func(void *arg){
    printf("这是第一个线程\n");
    mq_send(mq,"hello world",12,0); //发送消息
    return NULL;
}
void *second_thread_func(void *arg){
    printf("这是第二个线程\n");
    char mq_msg[100];
    int msg_len = 0;
    msg_len = mq_receive(mq,mq_msg,100,NULL); //接收消息
    printf("接收到的消息是：%.*s\n",msg_len, mq_msg);
    return NULL;
}
int main(int argc, char const *argv[])
{
    struct mq_attr attr;
    printf("主线程开始\n");
    //创建或打开消息队列
    attr.mq_msgsize = 100; //消息大小
    attr.mq_maxmsg = 10; //消息队列中最大消息数
    mq = mq_open(mq_name, O_RDWR | O_CREAT, 0666, &attr);
    //创建两个分线程
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, first_thread_func, NULL);
    pthread_create(&tid2, NULL, second_thread_func, NULL);


    //等待两个分线程执行完毕

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    printf("主线程结束\n");
    mq_close(mq);
    mq_unlink(mq_name);
    return 0;
}
